import * as THREE from "three";
import { CharacterSpawnPoint } from "./CharacterSpawnPoint";
import { World } from "./World";
import { ISpawnPoint } from "../interface/ISpawnPoint";
import { LoadingManager } from "../core/LoadingManager";

// 剧情
export class Scenario {

    public id: string;
    public name: string;
    public spawnAlways = false;
    public default = false;
    public world: World;
    public descriptionTitle: string;
    public descriptionContent: string;

    private rootNode: THREE.Object3D;
    private spawnPoints: CharacterSpawnPoint[];
    private invisible: boolean;
    private initialCameraAngle: number;

    constructor ( root: THREE.Object3D, world: World ) {
        this.rootNode = root;
        this.world = world;
        this.id = root.name;

        this.spawnPoints = [];
        this.invisible = false;

        const userData = root.userData;

        if ( userData.hasOwnProperty( "name" ) ) {
            this.name = userData.name;
        }

        if ( userData.hasOwnProperty( "default" ) && userData.default === "true" ) {
            this.default = true;
        }

        if ( userData.hasOwnProperty( "spawn_always" ) && userData.spawn_always === "true" ) {
            this.spawnAlways = true;
        }

        if ( userData.hasOwnProperty( "invisible" ) && userData.invisible === "true" ) {
            this.invisible = true;
        }

        if ( userData.hasOwnProperty( "desc_title" ) ) {
            this.descriptionTitle = userData.desc_title;
        }

        if ( userData.hasOwnProperty( "desc_content" ) ) {
            this.descriptionContent = userData.desc_content;
        }

        if ( userData.hasOwnProperty( "camera_angle" ) ) {
            this.initialCameraAngle = userData.camera_angle;
        }

        if ( !this.invisible ) this.createLaunchLink();

        root.traverse( child => {

            if ( child.hasOwnProperty( "userData" ) && child.userData.hasOwnProperty( "data" ) ) {

                const userData = child.userData;

                if ( userData.data === "spawn" ) {

                    const type = userData.type;

                    if ( type === "car" || type === "airplane" || type === "heli" ) {


                    } else if ( type === "player" ) {

                        const spawnPoint = new CharacterSpawnPoint( child );
                        this.spawnPoints.push( spawnPoint );

                    }

                }

            }

        } );
    }

    public createLaunchLink (): void {
        this.world.params[ this.name ] = () => {
            this.world.launchScenario( this.id );
        };
    }

    public launch ( loadingManager: LoadingManager, world: World ): void {

        this.spawnPoints.forEach( spawnPoint => {

            spawnPoint.spawn( loadingManager, world );

        } );

        console.log("launching");

        if ( !this.spawnAlways ) {


        }

    }

}